Step 8: POST Request

Let's include a route to create a bookmark.

HTTP MethodPOST
API Endpoint/bookmarks
Request Path Parameter
Request Query Parameter
Request BodyJSON object (bookmark attributes)
Response BodyJSON object (created bookmark)
Response Status201

Notes:

  • We use a POST method to create a bookmark.
  • The path (endpoint) is similar to the GET request we had earlier for receiving all bookmarks. So you can think about it as we are posting to the collection of bookmarks here (whereas before, we were going to read the collection of bookmarks).
  • We need to provide the attributes (title & url) for creating a bookmark. These attributes will be provided in the "body" (payload) of the request (we will see soon what that means!)
  • Once the bookmark is created, we will return the newly created resource. This practice is expected in the design of APIs.
  • We send a status code of 201 to signal the resource creation succeeded.

Add this route handler to src/routes/bookmarks.js:

router.post("/bookmarks", (req, res) => {
  const { title, url } = req.body;
  const bookmark = bookmarkDao.create({ title, url });
  res.status(201).json({
    status: 201,
    message: `Successfully created the following bookmark!`,
    data: bookmark,
  });
});

Notice how I have set the status code.

Also, notice how I have used req.body object to get the attributes of the bookmark. The client is expected to provide these attributes as JSON data in the request body. To allow Express parse the request body, we must add the following line somewhere in server.js (after app is declared):

app.use(express.json());

Save and commit the changes. Then, test this endpoint in Postman:

Untitled

Notice how I provided the bookmark attributes. Namely, I selected the “Body” tab in Postman. Then selected “raw” and “JSON” followed by providing the attributes “title” and “url” as a JSON object.